package cc.eguid.tools;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * nssm服务管理器
 * @author eguid
 */
public class NSSMServiceManager extends JFrame {
    // 配置文件
    private static final String CONFIG_FILE = "JNSM_config.properties";

    // NSSM 相关配置
    private static final String NSSM_ZIP_RESOURCE = "/nssm.zip";
    private static final String NSSM_EXE_NAME = "nssm.exe";
    private String currentDir;

    //logo配置
    private static final String LOGO_RESOURCE = "/logo.png";

    // UI 组件
    private JTextField nssmPathField;
    private JTextField serviceNameField;
    private JTextField javaPathField;
    private JTextField jarPathField;
    private JTextField jvmArgsField;
    private JTextArea logArea;
    private JButton browseNssmBtn, browseJavaBtn, browseJarBtn;
    private JButton installBtn, startBtn, stopBtn, uninstallBtn, saveConfigBtn;
    private JButton extractNssmBtn, autoDetectJavaBtn, checkServiceBtn, refreshServiceBtn;

    //日志控件
    private JCheckBox enableLoggingCheckbox;
    private JTextField customLogPathField;
    private JButton browseLogPathBtn;


    // 线程池用于延迟检查
    private ScheduledExecutorService scheduler;

    public NSSMServiceManager() {
        currentDir = System.getProperty("user.dir");
        scheduler = Executors.newScheduledThreadPool(1);

        initComponents();
        loadConfig();
        setTitle("Java服务管理工具（NSSM ）");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 650);
        setMinimumSize(new Dimension(800,640));
        setLocationRelativeTo(null);

        setWindowIcon();//设置图标
        setVisible(true);
    }

    @Override
    public void dispose() {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
        }
        super.dispose();
    }

    // 替换原来的setWindowIcon方法
    private boolean setWindowIcon() {
        // 优先尝试从资源加载
        ImageIcon icon=Utils.loadIconFromResource(LOGO_RESOURCE);
        if (icon != null) {
            setIconImage(icon.getImage());
            return true;
            // 尝试从外部文件加载
        }else if (loadIconFromFile(LOGO_RESOURCE)) {
            return true;
        }
        return false;
    }

    // 从文件系统加载图标
    private boolean loadIconFromFile(String filePath) {
        try {
            File iconFile = new File(filePath);
            if (iconFile.exists()) {
                ImageIcon icon = new ImageIcon(filePath);
                setIconImage(icon.getImage());
                return true;
            }
        } catch (Exception e) {
            System.err.println("加载图标文件失败: " + filePath + " - " + e.getMessage());
        }
        return false;
    }

    private void initComponents() {
        setLayout(new BorderLayout());

        JPanel configPanel = createConfigPanel();
        add(configPanel, BorderLayout.NORTH);

        JPanel buttonPanel = createButtonPanel();
        add(buttonPanel, BorderLayout.CENTER);

        JPanel logPanel = createLogPanel();
        add(logPanel, BorderLayout.SOUTH);

        SwingUtilities.invokeLater(this::initializeAutoDetection);
    }



    private void initializeAutoDetection() {
        Utils.checkAdminPrivileges(); // 添加权限检查

        // 先自动部署 NSSM
        autoDeployNssm();

        // 然后自动检测 Java 路径
        autoDetectJavaPath();
    }

    private JPanel createConfigPanel() {
        JPanel panel = new JPanel(new GridLayout(7, 3, 5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("服务配置"));

        // NSSM 路径配置
        panel.add(new JLabel("NSSM 路径（默认内置）:"));
        nssmPathField = new JTextField();
        panel.add(nssmPathField);

        browseNssmBtn = new JButton("浏览...");
        browseNssmBtn.addActionListener(e -> browseNssmPath());

        panel.add(browseNssmBtn);

        // Java 路径配置
        panel.add(new JLabel("Java 路径（默认当前运行环境）:"));
        javaPathField = new JTextField();
        panel.add(javaPathField);

        JPanel javaButtonPanel = new JPanel(new FlowLayout());
        browseJavaBtn = new JButton("浏览...");
        browseJavaBtn.addActionListener(e -> browseJavaPath());
        autoDetectJavaBtn = new JButton("自动检测");
        autoDetectJavaBtn.addActionListener(e -> autoDetectJavaPath());

        javaButtonPanel.add(browseJavaBtn);
        javaButtonPanel.add(autoDetectJavaBtn);
        panel.add(javaButtonPanel);

        // 服务名称
        panel.add(new JLabel("服务名称:"));
        serviceNameField = new JTextField("MyJavaService");
        panel.add(serviceNameField);

        JPanel serviceCheckPanel = new JPanel(new FlowLayout());
        checkServiceBtn = new JButton("检查服务");
        checkServiceBtn.addActionListener(e -> checkServiceStatus());
        refreshServiceBtn = new JButton("刷新状态");
        refreshServiceBtn.addActionListener(e -> refreshServiceStatus());

        serviceCheckPanel.add(checkServiceBtn);
        serviceCheckPanel.add(refreshServiceBtn);
        panel.add(serviceCheckPanel);

        // JAR 包路径
        panel.add(new JLabel("JAR 包路径:"));
        jarPathField = new JTextField();
        panel.add(jarPathField);
        browseJarBtn = new JButton("浏览...");
        browseJarBtn.addActionListener(e -> browseJarPath());
        panel.add(browseJarBtn);

        // JVM 参数
        panel.add(new JLabel("JVM 参数:"));
        jvmArgsField = new JTextField("-Xmx512m");
        panel.add(jvmArgsField);
        panel.add(new JLabel());

        //日志
        panel.add(new JLabel("是否启用日志输出:"));
        enableLoggingCheckbox = new JCheckBox("启用", true);
        enableLoggingCheckbox.addChangeListener(e->changeLoggingEnable());
        panel.add(enableLoggingCheckbox);
        panel.add(new JLabel());

        //换行
        panel.add(new JLabel("自定义日志路径:"));

        customLogPathField = new JTextField();
        panel.add(customLogPathField);
        browseLogPathBtn = new JButton("浏览...");
        browseLogPathBtn.addActionListener(e -> browseLogPath());
        panel.add(browseLogPathBtn);

        return panel;
    }

    // 添加浏览日志路径的方法
    private void browseLogPath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setDialogTitle("选择日志输出目录");
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            customLogPathField.setText(chooser.getSelectedFile().getAbsolutePath());
            saveConfig();
        }
    }

    private void changeLoggingEnable(){
        if(enableLoggingCheckbox.isSelected()){
            customLogPathField.setEnabled(true);
            browseLogPathBtn.setEnabled(true);
        }else{
            customLogPathField.setEnabled(false);
            browseLogPathBtn.setEnabled(false);
        }
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        panel.setBorder(BorderFactory.createTitledBorder("服务操作"));

        installBtn = new JButton("安装服务");
        installBtn.addActionListener(e -> installService());

        startBtn = new JButton("启动服务");
        startBtn.addActionListener(e -> startService());

        stopBtn = new JButton("停止服务");
        stopBtn.addActionListener(e -> stopService());

        uninstallBtn = new JButton("卸载服务");
        uninstallBtn.addActionListener(e -> uninstallService());

        saveConfigBtn = new JButton("保存配置");
        saveConfigBtn.addActionListener(e -> saveConfig());

        panel.add(installBtn);
        panel.add(startBtn);
        panel.add(stopBtn);
        panel.add(uninstallBtn);
        panel.add(saveConfigBtn);

        return panel;
    }

    private JPanel createLogPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("操作日志"));

        logArea = new JTextArea(6, 60);
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    // 检查服务状态的方法
    private void checkServiceStatus() {
        String serviceName = serviceNameField.getText().trim();
        if (serviceName.isEmpty()) {
            showError("请输入服务名称");
            return;
        }

        logArea.append(">>> 手动检查服务状态: " + serviceName + "\n");
        checkServiceExistsWithDetails(serviceName);
    }

    // 刷新服务状态（快速检查）
    private void refreshServiceStatus() {
        String serviceName = serviceNameField.getText().trim();
        if (serviceName.isEmpty()) {
            showError("请输入服务名称");
            return;
        }

        logArea.append(">>> 刷新服务状态: " + serviceName + "\n");
        quickCheckServiceStatus(serviceName);
    }

    // 自动检测 Java 路径的核心方法
    private void autoDetectJavaPath() {
        logArea.append(">>> 开始自动检测 Java 路径...\n");

        List<String> possibleJavaPaths = new ArrayList<>();

        // 1. 检测当前运行环境的 Java 路径（最可靠）
        String currentJavaHome = System.getProperty("java.home");
        if (currentJavaHome != null) {
            String javaExePath = Utils.findJavaExeInHome(currentJavaHome);
            if (javaExePath != null) {
                possibleJavaPaths.add(javaExePath);
                logArea.append("✓ 检测到当前运行环境 Java: " + javaExePath + "\n");
            }
        }

        // 2. 检测 JAVA_HOME 环境变量
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            String javaExePath = Utils.findJavaExeInHome(javaHome);
            if (javaExePath != null) {
                possibleJavaPaths.add(javaExePath);
                logArea.append("✓ 检测到 JAVA_HOME: " + javaExePath + "\n");
            }
        }

        // 3. 检测 PATH 环境变量中的 Java
        possibleJavaPaths.addAll(Utils.findJavaInPath());

        // 4. 搜索常见安装路径
        possibleJavaPaths.addAll(Utils.searchCommonJavaPaths());

        // 去重并选择最佳路径
        List<String> uniquePaths = possibleJavaPaths.stream().distinct().collect(Collectors.toList());

        if (!uniquePaths.isEmpty()) {
            // 优先选择当前运行环境的 Java
            String bestChoice = uniquePaths.get(0);
            for (String path : uniquePaths) {
                if (path.contains(currentJavaHome)) {
                    bestChoice = path;
                    break;
                }
            }

            javaPathField.setText(bestChoice);
            logArea.append("✓ 自动选择 Java 路径: " + bestChoice + "\n");
            saveConfig();
        } else {
            logArea.append("✗ 未找到可用的 Java 路径，请手动选择\n");
        }
    }

    //解压内置的nssm
    private boolean extractNssmFromResource() {
        logArea.append(">>> 开始解压内置 NSSM...\n");
        try {
            InputStream zipStream = getClass().getResourceAsStream(NSSM_ZIP_RESOURCE);
            if (zipStream == null) {
                logArea.append("✗ 找不到内置的 NSSM 压缩包资源: " + NSSM_ZIP_RESOURCE + "\n");
                return false;
            }

            File nssmDir = new File(currentDir, "nssm");
            if (!nssmDir.exists()) {
                nssmDir.mkdirs();
            }

            ZipInputStream zis = new ZipInputStream(zipStream);
            ZipEntry entry;
            boolean nssmExtracted = false;

            while ((entry = zis.getNextEntry()) != null) {
                String entryName = entry.getName();
                File outputFile = new File(nssmDir, entryName);

                if (entryName.contains("nssm") && entryName.endsWith(".exe")) {
                    logArea.append("解压文件: " + entryName + "\n");
                    outputFile.getParentFile().mkdirs();

                    FileOutputStream fos = new FileOutputStream(outputFile);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, length);
                    }
                    fos.close();

                    nssmExtracted = true;
                    String nssmPath = outputFile.getAbsolutePath();
                    nssmPathField.setText(nssmPath);
                    logArea.append("✓ NSSM 已解压到: " + nssmPath + "\n");
                }
                zis.closeEntry();
            }
            zis.close();

            if (nssmExtracted) {
                logArea.append("✓ NSSM 解压完成\n");
                String nssmPath = nssmPathField.getText();
                customLogPathField.setText(nssmPath.substring(0, nssmPath.length() - 9));
                saveConfig();
                return true;
            } else {
                logArea.append("✗ 在压缩包中未找到 nssm.exe\n");
                return false;
            }

        } catch (IOException ex) {
            logArea.append("✗ 解压 NSSM 时出错: " + ex.getMessage() + "\n");
            return false;
        }
    }

    //自动部署nssm
    private void autoDeployNssm() {
        logArea.append(">>> 自动检查 NSSM 环境...\n");

        String currentNssmPath = nssmPathField.getText();
        if (currentNssmPath != null && !currentNssmPath.trim().isEmpty()) {
            File nssmFile = new File(currentNssmPath);
            if (nssmFile.exists()) {
                logArea.append("✓ 检测到现有 NSSM 路径: " + currentNssmPath + "\n");
                return;
            }
        }

        File localNssm = new File(currentDir, "nssm/" + NSSM_EXE_NAME);
        if (localNssm.exists()) {
            nssmPathField.setText(localNssm.getAbsolutePath());
            logArea.append("✓ 检测到本地 NSSM: " + localNssm.getAbsolutePath() + "\n");
            return;
        }

        logArea.append("未找到 NSSM，尝试解压内置版本...\n");
        if (extractNssmFromResource()) {
            logArea.append("✓ NSSM 自动部署完成\n");
        } else {
            logArea.append("⚠ 请手动选择 NSSM 路径或点击'解压内置NSSM'按钮\n");
        }
    }

    //浏览nssm路径
    private void browseNssmPath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("NSSM Executable", "exe"));
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            nssmPathField.setText(chooser.getSelectedFile().getAbsolutePath());
            saveConfig();
        }
    }

    //浏览java运行路径
    private void browseJavaPath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Java Executable", "exe"));
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            javaPathField.setText(chooser.getSelectedFile().getAbsolutePath());
            saveConfig();
        }
    }

    //浏览jar路径
    private void browseJarPath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JAR Files", "jar"));
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            jarPathField.setText(chooser.getSelectedFile().getAbsolutePath());
            saveConfig();
        }
    }

    //执行命令
    private void executeCommand(String command, String description) {

        logArea.append(">>> " + description + "...\n");
        logArea.append("执行命令: " + command + "\n");

        try {
            Process process = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), "GBK"));

            String line;
            while ((line = reader.readLine()) != null) {
                logArea.append("输出: " + line + "\n");
            }
            while ((line = errorReader.readLine()) != null) {
                logArea.append("错误: " + line + "\n");
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                logArea.append("✓ " + description + " 成功\n");
            } else {
                logArea.append("✗ " + description + " 失败，退出码: " + exitCode + "\n");
                // 根据退出码提供具体建议
                suggestSolution(exitCode, description);
            }

        } catch (IOException | InterruptedException ex) {
            logArea.append("✗ 执行命令时出错: " + ex.getMessage() + "\n");
        }
        logArea.append("----------------------------------------\n");
    }

    // 根据退出码提供解决方案
    private void suggestSolution(int exitCode, String operation) {
        switch (exitCode) {
            case 3:
                logArea.append("💡 解决方案: 系统找不到指定的路径。请检查:\n");
                logArea.append("   1. NSSM路径是否正确\n");
                logArea.append("   2. Java可执行文件是否存在\n");
                logArea.append("   3. JAR包路径是否正确\n");
                logArea.append("   4. 路径中是否包含空格或特殊字符\n");
                break;
            case 5:
                logArea.append("💡 解决方案: 访问被拒绝。请以管理员身份运行此程序\n");
                break;
            case 1060:
                logArea.append("💡 解决方案: 指定的服务未安装\n");
                break;
            default:
                logArea.append("💡 请检查所有路径是否正确，并以管理员身份运行\n");
        }
    }

    // 诊断方法
    private void diagnoseServiceError(String serviceName) {
        logArea.append(">>> 开始诊断服务错误...\n");

        // 检查服务是否已存在
        try {
            Process process = Runtime.getRuntime().exec("sc query \"" + serviceName + "\"");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            boolean serviceExists = false;
            while ((line = reader.readLine()) != null) {
                logArea.append("服务状态: " + line + "\n");
                if (line.contains("STATE")) {
                    serviceExists = true;
                }
            }
            process.waitFor();

            if (!serviceExists) {
                logArea.append("⚠ 服务不存在，可能需要重新安装\n");
            }
        } catch (Exception ex) {
            logArea.append("诊断错误: " + ex.getMessage() + "\n");
        }
    }



    //安装服务
    private void installService() {
        if (!validateConfig()) return;

        saveConfig();//安装前保存配置

        String nssmPath = nssmPathField.getText();
        String serviceName = serviceNameField.getText();
        String javaPath = javaPathField.getText();
        String jarPath = jarPathField.getText();
        String jvmArgs = jvmArgsField.getText();

        //检查是否重复安装
        if (Utils.checkServiceExists(serviceName)) {
            int result = JOptionPane.showConfirmDialog(this,
                    "服务 '" + serviceName + "' 已存在。是否重新安装？",
                    "服务已存在", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.YES_OPTION) {
                // 先卸载现有服务
                uninstallService();
            } else {
                return;
            }
        }

        // 添加详细路径检查
        logArea.append(">>> 详细路径检查:\n");
        logArea.append("NSSM路径: " + nssmPath + " [存在: " + new File(nssmPath).exists() + "]\n");
        logArea.append("Java路径: " + javaPath + " [存在: " + new File(javaPath).exists() + "]\n");
        logArea.append("JAR路径: " + jarPath + " [存在: " + new File(jarPath).exists() + "]\n");

        // 构建安装命令 - 使用更安全的方式
        String command = String.format("\"%s\" install \"%s\" \"%s\" %s -jar \"%s\"",
                nssmPath, serviceName, javaPath, jvmArgs, jarPath);

        executeCommand(command, "安装服务");

        boolean enableLogging = enableLoggingCheckbox.isSelected();

        //是否开启日志
        if (enableLogging) {
            String logPath;
            if (customLogPathField.getText() != null && !customLogPathField.getText().trim().isEmpty()) {
                logPath = customLogPathField.getText().trim();
            } else {
                logPath = nssmPath.substring(0, nssmPath.length() - 9);
            }

            // 确保日志目录存在
            File logDir = new File(logPath);
            if (!logDir.exists()) {
                logDir.mkdirs();
            }

            // 配置服务标准输出日志
            String command2 = String.format("\"%s\" set \"%s\" AppStdout \"%s\\%s-info.log\"",
                    nssmPath, serviceName, logPath, serviceName);
            executeCommand(command2, "配置服务日志输出路径");

            // 配置服务错误输出日志
            String command3 = String.format("\"%s\" set \"%s\" AppStderr \"%s\\%s-error.log\"",
                    nssmPath, serviceName, logPath, serviceName);
            executeCommand(command3, "配置服务错误日志输出路径");

            // 设置日志轮转
            String command4 = String.format("\"%s\" set \"%s\" AppRotateFiles 1",
                    nssmPath, serviceName);
            executeCommand(command4, "启用日志轮转");
        }
        // 安装后立即检查服务状态
        diagnoseServiceError(serviceName);
    }

    //开始服务
    private void startService() {
        if (!validateConfig()) return;

        String nssmPath = nssmPathField.getText();
        String serviceName = serviceNameField.getText();
        // 先检查服务状态
        diagnoseServiceError(serviceName);

        String command = String.format("\"%s\" start \"%s\"", nssmPath, serviceName);

        executeCommand(command, "启动服务");
    }

    //停止服务
    private void stopService() {
        if (!validateConfig()) return;

        String nssmPath = nssmPathField.getText();
        String serviceName = serviceNameField.getText();
        String command = String.format("\"%s\" stop \"%s\"", nssmPath, serviceName);

        executeCommand(command, "停止服务");
    }

    //卸载服务
    private void uninstallService() {
        if (!validateConfig()) return;

        String nssmPath = nssmPathField.getText();
        String serviceName = serviceNameField.getText();
        String command = String.format("\"%s\" remove \"%s\" confirm", nssmPath, serviceName);

        executeCommand(command, "卸载服务");
    }

    private boolean validateConfig() {
        if (nssmPathField.getText().trim().isEmpty()) {
            showError("请选择 NSSM 路径或解压内置 NSSM");
            return false;
        }
        if (serviceNameField.getText().trim().isEmpty()) {
            showError("请输入服务名称");
            return false;
        }
        if (javaPathField.getText().trim().isEmpty()) {
            showError("请选择 Java 路径");
            return false;
        }
        if (jarPathField.getText().trim().isEmpty()) {
            showError("请选择 JAR 包路径");
            return false;
        }

        File nssmFile = new File(nssmPathField.getText());
        if (!nssmFile.exists()) {
            showError("NSSM 文件不存在，请重新选择或解压");
            return false;
        }

        File javaFile = new File(javaPathField.getText());
        if (!javaFile.exists()) {
            showError("Java 可执行文件不存在，请重新选择");
            return false;
        }

        return true;
    }

    //显示错误
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    //保存配置
    private void saveConfig() {
        try {
            Properties props = new Properties();
            props.setProperty("nssm.path", nssmPathField.getText());
            props.setProperty("service.name", serviceNameField.getText());
            props.setProperty("java.path", javaPathField.getText());
            props.setProperty("jar.path", jarPathField.getText());
            props.setProperty("jvm.args", jvmArgsField.getText());
            //日志配置
            props.setProperty("logging.enabled", String.valueOf(enableLoggingCheckbox.isSelected()));
            props.setProperty("log.path", customLogPathField.getText());

            props.store(Files.newOutputStream(Paths.get(CONFIG_FILE)),
                    "NSSM Service Manager Configuration");

            logArea.append("✓ 配置已保存到 " + CONFIG_FILE + "\n");
        } catch (IOException ex) {
            logArea.append("✗ 保存配置失败: " + ex.getMessage() + "\n");
        }
    }

    //加载配置
    private void loadConfig() {
        File configFile = new File(CONFIG_FILE);
        if (configFile.exists()) {
            try {
                Properties props = new Properties();
                props.load(Files.newInputStream(Paths.get(CONFIG_FILE)));

                nssmPathField.setText(props.getProperty("nssm.path", ""));
                serviceNameField.setText(props.getProperty("service.name", "MyJavaService"));
                javaPathField.setText(props.getProperty("java.path", ""));
                jarPathField.setText(props.getProperty("jar.path", ""));
                jvmArgsField.setText(props.getProperty("jvm.args", "-Xmx512m"));

                //日志
                enableLoggingCheckbox.setSelected(Boolean.parseBoolean(props.getProperty("logging.enabled", "true")));
                customLogPathField.setText(props.getProperty("log.path", ""));
                logArea.append("✓ 配置已从 " + CONFIG_FILE + " 加载\n");
            } catch (IOException ex) {
                logArea.append("✗ 加载配置失败: " + ex.getMessage() + "\n");
            }
        }
    }

    //快速检查服务状态
    private void quickCheckServiceStatus(String serviceName) {
        try {
            Process process = Runtime.getRuntime().exec("sc query \"" + serviceName + "\"");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("STATE")) {
                    logArea.append("当前状态: " + line.trim() + "\n");
                    break;
                }
            }
            process.waitFor();

        } catch (Exception ex) {
            logArea.append("快速检查失败: " + ex.getMessage() + "\n");
        }
    }

    // 延迟检查服务状态
    private void delayedServiceCheck(String serviceName, int delaySeconds, String operation) {
        logArea.append("⏳ " + delaySeconds + "秒后自动检查服务状态...\n");

        scheduler.schedule(() -> {
            SwingUtilities.invokeLater(() -> {
                logArea.append(">>> 自动检查 (" + operation + "后): " + serviceName + "\n");
                checkServiceExistsWithDetails(serviceName);
            });
        }, delaySeconds, TimeUnit.SECONDS);
    }

    // 详细检查服务状态
    private void checkServiceExistsWithDetails(String serviceName) {
        try {
            logArea.append("正在检查服务状态...\n");

            // 方法1: 使用 sc query 命令
            Process process = Runtime.getRuntime().exec("sc query \"" + serviceName + "\"");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));

            String line;
            boolean serviceFound = false;
            while ((line = reader.readLine()) != null) {
                logArea.append("SC查询: " + line + "\n");
                if (line.contains("STATE")) {
                    serviceFound = true;
                    // 解析服务状态
                    if (line.contains("RUNNING")) {
                        logArea.append("✓ 服务正在运行\n");
                    } else if (line.contains("STOPPED")) {
                        logArea.append("⚠ 服务已停止\n");
                    } else if (line.contains("START_PENDING")) {
                        logArea.append("⏳ 服务正在启动...\n");
                    } else if (line.contains("STOP_PENDING")) {
                        logArea.append("⏳ 服务正在停止...\n");
                    }
                }
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                if (serviceFound) {
                    logArea.append("✓ 服务已存在系统中\n");
                } else {
                    logArea.append("✗ 服务不存在或无法访问\n");
                }
            } else if (exitCode == 1060) {
                logArea.append("✗ 服务不存在 (错误 1060)\n");
            }

            // 方法2: 使用 wmic 检查
            logArea.append("--- 使用WMIC进一步检查 ---\n");
            Process wmicProcess = Runtime.getRuntime().exec(
                    "wmic service where \"name='" + serviceName + "'\" get name,state,status /format:value");

            BufferedReader wmicReader = new BufferedReader(
                    new InputStreamReader(wmicProcess.getInputStream(), "GBK"));

            boolean wmicFound = false;
            while ((line = wmicReader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    logArea.append("WMIC: " + line + "\n");
                    wmicFound = true;
                }
            }
            wmicProcess.waitFor();

            if (!wmicFound) {
                logArea.append("WMIC: 未找到服务信息\n");
            }

            logArea.append("----------------------------------------\n");

        } catch (Exception ex) {
            logArea.append("✗ 检查服务状态时出错: " + ex.getMessage() + "\n");
        }
    }

}
